package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.query.EmployeeQueryObject;
import cn.wolfcode.rbac.service.IDepartmentService;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.IRoleService;
import cn.wolfcode.rbac.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) throws  Exception{
        model.addAttribute("result", employeeService.query(qo));
        model.addAttribute("depts", departmentService.list());
        return "employee/list";
    }
    @RequestMapping("/input")
    public String input(Long id, Model model) throws  Exception{
        if(id != null){
            model.addAttribute("entity", employeeService.get(id));
        }
        model.addAttribute("depts", departmentService.list());
        model.addAttribute("roles", roleService.list());
        return "employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee entity, Long[] ids) throws  Exception{

        if(entity.getId() != null){
            employeeService.update(entity, ids);
        }else{
            employeeService.save(entity, ids);
        }
        return "redirect:/employee/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id) throws  Exception{
        JSONResult result = new JSONResult();
        try {
            if (id != null) {
                employeeService.delete(id);
            }
        }catch (Exception e){
            result.mark(e.getMessage());
        }
        return result;
    }


}
